import webview
# from flask import Flask, render_template, jsonify, request
import json
from functools import wraps
import os
import tkinter as tk
from tkinter.filedialog import askdirectory
from threading import Thread
import re
import model

import multiprocessing

# STATIC_FOLDER = 'static'
# app = Flask(__name__, template_folder=STATIC_FOLDER, static_folder=STATIC_FOLDER)

tasks = []

def update_status(file,name):
    s = None
    save_json_content = []
    with open(file, 'r',encoding="utf-8") as json_file:
        save_json_content = json.load(json_file)

    for item in save_json_content:
        if(item["file_name"] == name and item["status"] == 0):

            with open(file, 'w',encoding="utf-8") as json_file2:
                item["status"] = 1
                s = item["status"]
                json.dump(save_json_content, json_file2, indent=4)
            break
    return s

class Api():
    json_file_path = 'cache.json'

    def select_dir(self):  # 选择目录
        result = window.create_file_dialog(webview.FOLDER_DIALOG)
        print(result)
        return result[0] if result else ''

    def select_file(self,n):  # 选择文件
        types = ['MP3 File (*.mp3)','MP4 File (*.mp4)','WAV File (*.wav)']
        file_types = ('{}'.format(types[n]), 'All files (*.*)')
        result = window.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=True, file_types=file_types)
        print(result)
        return result[0] if result else ''

    
    def save_file(self):  # 选择文件
        # result = os.popen("explorer /select,C:\\")
        result = ""
        root = tk.Tk()
        root.withdraw()  # 实现主窗口隐藏
        result = askdirectory() #使用askdirectory()方法返回文件夹的路径
        root.destroy()

        return result if result else ''
    
    def make_task(self,f,s,s_cpu,language,model_name):  # 生成任务

        # json_file_path = 'cache.json'
        data = []
        save_json_content = []
        result = re.findall(r'[^\\/:*?"<>|\r\n]+$', f, flags=0)
        file_suffix = os.path.splitext(f)[1][1:]
        with open(self.json_file_path, 'r',encoding="utf-8") as json_file:
            save_json_content = json.load(json_file)
        with open(self.json_file_path, 'w',encoding="utf-8") as json_file2:
            result_json = {
                "file_path": f,
                "save_path": s,
                "s_cpu": s_cpu,
                "language":language,
                "file_name":result[0],
                "model":model_name,
                "status": 0,
                "file_type":file_suffix
            }
            save_json_content.append(result_json)
            json.dump(save_json_content, json_file2, indent=4) 

        data = [result[0],file_suffix]
        return data if result else ''

    def run(self): # 运行模型开始识别
        data = None
        with open("cache.json","r",encoding="utf8") as file:
            data = json.load(file)

        for x in range(len(data)):
            if(data[x]["status"] == 0):
                try:
                    # t = Thread(target=model.model, args=(data[x],))
                    t = multiprocessing.Process(target=model.model, args=(data[x],))
                    t.daemon = True  #随主线程退出
                    t.name = data[x]["file_name"]
                    tasks.append(t)
                    t.start()
                except:
                    print("Error: unable to start thread")

        return None
    
    def monitor(self): #监控线程

        result = []
        
        if(len(tasks) == 0):
            return result

        print("runing...")
        for task in tasks:
            item = {}
            name = task.name
            if(task.is_alive()):
                # print(tasks[i].name)
                item["status"] = 0
            else:

                item["status"] = update_status(self.json_file_path,name) #修改状态
                print(item["status"])
                tasks.remove(task)
            item["name"] = name
            result.append(item)


        return result

    def task_show(self):
        data = []
        with open("cache.json","r",encoding="utf8") as file:
            data = json.load(file)
        return data

    def task_run_show(self):  # 查看需要运行的文件
        data = []
        with open("cache.json","r",encoding="utf8") as file:
            result = json.load(file)
            for item in result:
                if(item["status"] == 0):
                    data.append(item)
        return data

    def task_stop(self):  #任务终止
        try:
            for task in tasks:
                task.terminate() 
        except:
            return False
        return True
    
    def delete_task(self,name): #删除任务缓存
        data = []
        self.single_task_stop(name)
        with open("cache.json","r",encoding="utf8") as file:
            data = json.load(file)
        for item in data:
            if(item["file_name"] == name):
                data.remove(item)
        with open("cache.json","w",encoding="utf8") as file2:
            json.dump(data, file2, indent=4) 
        return True

    def single_task_run(self,name):  #单个运行
        data = []
        with open("cache.json","r",encoding="utf8") as file:
            data = json.load(file)

        for item in data:

            for t in tasks:   #重新启动
                if(t.name == name):
                    t.start()
                    return True
            
            if(item["file_name"] == name):
                item["status"]  = 0
                with open("cache.json","w",encoding="utf8") as file2:
                    json.dump(data, file2, indent=4)
                t1 = multiprocessing.Process(target=model.model, args=(item,))
                t1.daemon = True  #随主线程退出
                t1.name = item["file_name"]
                tasks.append(t1)
                t1.start()
                return True
    
    def single_task_stop(self,name):
        data = []
        with open("cache.json","r",encoding="utf8") as file:
            data = json.load(file)

        for item in data:
            if(item["file_name"] == name):
                item["status"] = 2
                print("done")
        with open("cache.json","w",encoding="utf8") as file2:
            json.dump(data, file2, indent=4)

        for t in tasks:
            if(t.name == name):
                t.terminate()
                return True
    
    def open_explore(self,name): #打开文件夹
        data = []
        with open("cache.json", "r", encoding="utf8") as file:
            data = json.load(file)
        for item in data:
            if(item["file_name"] == name):
                os.system("start explorer {}".format(item["save_path"].replace("/",'\\')))
                break
        return None

if __name__ == '__main__':
    chinese = {
        'global.quitConfirmation': u'确定关闭?',
    }

    api = Api()
    window = webview.create_window('demo', url="./static/index.html", js_api=api,width=1100,height=800)
    webview.start(localization=chinese, debug=True,http_server=True)

